package com.tanhua.dubbo.api;

import com.tanhua.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存访客记录
     * @param visitors
     */
    @Override
    public void save(Visitors visitors) {
        //一个用户对另一个用户同一天只保存一条访客记录
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                                    .and(("visitorUserId")).is(visitors.getVisitorUserId())
                                    .and("visitDate").is(visitors.getDate()));
        if(!mongoTemplate.exists(query,Visitors.class)){
            mongoTemplate.save(visitors);
        }
    }

    /**
     * 获取访客记录
     *
     * @param date
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> getVisitors(Long userId, Long date) {
        //构造查询条件
        Criteria criteria = Criteria.where("userId").is(userId);
        //如果date不为空，添加时间条件
        if(date != null){
            criteria.and("date").gt(date);
        }
        Query query = Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        return mongoTemplate.find(query,Visitors.class);
    }
}
